import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sp_util/sp_util.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:yp/config/config.dart';
import 'package:yp/services/api.dart';

import '../../../helper.dart';
import 'state.dart';

class SelectShippingAddressLogic extends GetxController {
  final state = SelectShippingAddressState();

  @override
  void onInit() {
    super.onInit();
    if (SpUtil.getString('token') != null &&
        SpUtil.getString('token').isNotEmpty) {
      getReceivingAddressList();
      getCities();
      getAddress();
    }
  }

  /// 获取收货地址列表数据
  void getReceivingAddressList() {
    Api.getReceivingAddressList({'access_token': SpUtil.getString('token')})
        .listen((event) {
      print("event==========$event");
      if (event["code"] == 0 && event["member_adrs"] != null) {
        state.receivingAddressList = event["member_adrs"];
        state.receivingAddressList.insert(0, {});
      }
      update();
    });
  }

  /// 获取已开通城市列表
  void getCities() {
    Api.getCity({'access_token': SpUtil.getString('token')}).listen((event) {
      print("getCities ==========$event");
      if (event["code"] == 0 && event["citys"] != null) {
        state.cityList = event["citys"];
      }
      update();
    });
  }

  /// 周边搜索
  void surroundingSearch(Map<String, dynamic> params) {
    Api.surroundingSearch(params).listen((event) {
      if (event["code"] == 0 && event["address_list"] != null) {
        var location = jsonDecode(event['address']['location_name']);
        print("周边搜索==========$event");

        state.nearbyAddressList = event["address_list"];
        if (state.nearbyAddressList.length > 20) {
          state.nearbyAddressList = state.nearbyAddressList.sublist(0, 20);
        }
        state.nearbyAddressList.insert(0, {});
        state.nearbyAddressList.add({});
        update();
      }
    });
  }

  _alertDialog() async {
    var alertDialogs = await showDialog(
        context: Get.context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text("请尝试配置定位权限，重新获取位置信息"),
            actions: <Widget>[
              TextButton(
                  child: Text("取消"),
                  onPressed: () => Navigator.pop(context, "cancel")),
              TextButton(
                  child: Text("确定"),
                  onPressed: (){
                    Navigator.pop(context, "yes");
                    openAppSettings();
                  }),
            ],
          );
        });
    return alertDialogs;
  }

  getAddress() async {
    var status = await Permission.location.status;
    if (status != PermissionStatus.granted) {
      if(Platform.isIOS){
        toast('请尝试配置定位权限，重新获取位置信息');
      }else{
        _alertDialog();
      }
      return;
    }
    Map locationMap = SpUtil.getObject(Config.USER_CURRENT_LOCATION);
    String addressResult = "正在定位";
    print("locationMap======$locationMap");
    if (locationMap == null || locationMap.length == 0) {
      addressResult = "定位失败";
    } else {
      // if (locationMap["userSelectAddress"] == null ||
      //     locationMap["userSelectAddress"].length == 0) {
      //   if (locationMap["AMapResult"] == null ||
      //       locationMap["AMapResult"].length == 0) {
      //     addressResult = "定位失败";
      //   } else {
      //     addressResult = locationMap["AMapResult"]['address'];
      //   }
      // }
      addressResult = locationMap["AMapResult"]['address'];

      state.address = addressResult;
      update();
    }
  }

  /// 比较map是否相等（值比较）
  bool mapEquals<T, U>(Map<T, U> a, Map<T, U> b) {
    if (a == null) return b == null;
    if (b == null || a.length != b.length) return false;
    if (identical(a, b)) return true;
    for (final T key in a.keys) {
      if (!b.containsKey(key) || b[key] != a[key]) {
        return false;
      }
    }
    return true;
  }
}
